<!--
 * @title: 列表参照
 * @params1: singleSelect 默认false 是否单选，true为单选，false为多选
 * @params2: dataType 默认id 传入和传出的字段，可选值id或code，若为code，则v-mode的值为code1,code2,code3的形式，id为id1,id2,id3的形式
 * @params2: nameType 默认name 传入和传出的显示字段
 * @params3: value v-model绑定的值，打开参照可绑定value值为默认值，选择后，会返回value的值，value值类型根据dataType选择
 * @params4: initDisplayData 初始显示值，比如dispdeptid
 * @params5: isDisplayDefaultElement 是否显示默认的选择元素
 * @params6: refTitle 是否显示默认的选择元素
 * @params7: queryDataUrl 必传，根据树节点查询子节点的url
 * @params8: queryDataParam 根据树节点查询子节点的参数
 * @params9: treeQueryKey 列表用于查询的key值
 * @params10: disabled 禁用
 * @params11: width 默认input框的宽度
 * @method1: confirm 用户选择后，返回选择的对象数组
 * @slot1: default 可替换默认的选择框元素
 * @slot2: search 可替换默认的搜索条件，带有queryParam
 * @description: 用户参照选择组件
 * @fileName: RefList.vue
 * @author: zhanglongfei
 * @date: 2019-08-24 14:00:17
!-->
<template>
  <div>
    <slot>
      <el-input v-model="initDisplayData" :readonly="true" :style="{ width: width }" :disabled="true" class="tl-ref-selector" :class="{ disabled: buttonDisabled }" v-if="isDisplayDefaultElement">
        <el-button slot="append" icon="el-icon-search" @click="openRefDialog" :disabled="buttonDisabled"></el-button>
      </el-input>
    </slot>
    <el-dialog :visible.sync="refVisible" ref="refDailog" :title="refTitle" :close-on-click-modal="false" v-dialogDrag width="700px" :modal-append-to-body="false" :append-to-body="true" class="tl-ref tl-dialog tl-ref-list" @open="open">
      <el-row class="top-category">
        <el-col :span="24">
          <el-form ref="searchForm" :inline="true" class="tl-search-form" :inline-message="true" @submit.native.prevent>
            <slot name="search" v-bind:queryParam="queryParam">
              <el-form-item>
                <el-input v-model.trim="queryParam.qry_name" clearable placeholder="输入名称搜索" @keyup.enter.native="doQueryBySearch" style="width:150px;" />
              </el-form-item>
              <el-form-item>
                <el-input v-model.trim="queryParam.qry_code" clearable placeholder="输入编码搜索" @keyup.enter.native="doQueryBySearch" style="width:150px;" />
              </el-form-item>
            </slot>
            <el-button type="primary" @click="doQueryBySearch">全局搜索</el-button>
            <el-button type="primary" @click="doSelectAll" v-if="!singleSelect">全选</el-button>
          </el-form>
          <el-scrollbar class="scroll-category">
            <el-row v-loading="isLoading" v-if="dataList.length > 0">
              <el-col :span="24">
                <template v-for="item in dataList">
                  <el-tag type="info" :key="'a' + item.id" v-if="selectedData.findIndex((m) => m.id === item.id) === -1" @click="addData(item)">{{ item[nameType] }}</el-tag>
                  <el-tag type="success" :key="'b' + item.id" closable v-else @close="removeData(item)">{{ item[nameType] }}</el-tag>
                </template>
                <el-button type="text" v-if="!noMore" icon="el-icon-more" @click="doQueryMore">加载更多({{ queryParam.currentPage }}/{{ queryParam.totalPage }})</el-button>
              </el-col>
            </el-row>
            <p v-else class="no-info">此条件下没有信息</p>
          </el-scrollbar>
        </el-col>
      </el-row>
      <el-row class="bottom-selected">
        <el-col :span="24">
          <el-row>
            <el-col :span="12">
              <h2>已选择数据({{ selectedData.length }})</h2>
            </el-col>
            <el-col :span="12" class="selected-control">
              <el-button type="text" icon="el-icon-delete" class="btn-clear" @click="doClearAll">清空所有选择</el-button>
            </el-col>
          </el-row>
          <el-scrollbar class="scroll-selected">
            <el-row v-loading="isLoading" class="user-list">
              <el-col :span="24">
                <el-tag type="success" v-for="item in selectedData" :key="item.id" closable @close="removeData(item)">{{ item[nameType] }}</el-tag>
              </el-col>
            </el-row>
          </el-scrollbar>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button @click="doCancelEdit">取消</el-button>
        <el-button type="primary" @click="doConfirm" v-if="!disabled">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { putAction, getAction, postAction } from '@tapui/utils/http'
/** 常量 */
import { CHECK_CENTER } from '@/const/const'
export default {
  name: 'TlRefList',
  data() {
    return {
      refVisible: false,
      selectedData: [],
      dataList: [],
      treeList: [],
      isLoading: false,
      queryParam: {
        sidx: 'sortcode',
        sord: 'asc',
        qry_name: '',
        qry_code: '',
        currentPage: 1,
        pageSize: 20,
        totalPage: 0
      },
      disabledScrollSearch: true,
      displayData: ''
    }
  },
  inject: {
    elForm: {
      default: ''
    }
  },
  props: {
    singleSelect: {
      default: false,
      type: Boolean
    },
    dataType: {
      default: 'id',
      type: String
    },
    nameType: {
      default: 'name',
      type: String
    },
    width: {
      default: '',
      type: String
    },
    value: {
      default: '',
      type: [String, Number]
    },
    initDisplayData: {
      default: '',
      type: String
    },
    isDisplayDefaultElement: {
      default: true,
      type: Boolean
    },
    refTitle: {
      default: '参照选择',
      type: String
    },
    queryDataUrl: {
      default: '',
      type: String,
      required: true
    },
    queryDataParam: {
      default: function() {
        return {}
      },
      type: Object
    },
    disabled: Boolean,
    // 传入查询参数（外部）
    externalQueryParam: {
      default: function() {
        return {}
      },
      type: Object
    },
    // 传入最大数
    maxNum: {
      default: 0,
      type: Number
    }
  },
  computed: {
    noMore() {
      if (this.disabledScrollSearch) {
        return true
      } else {
        return this.dataList.length === 0 || this.queryParam.totalPage <= this.queryParam.currentPage
      }
    },
    buttonDisabled() {
      return typeof this.disabled === 'boolean' ? this.disabled : (this.elForm || {}).disabled
    }
  },
  methods: {
    doCancelEdit() {
      this.refVisible = false
    },
    doConfirm() {
      this.displayData = ''
      let returnData = ''
      this.selectedData.forEach((item) => {
        this.displayData += item[[this.nameType]] + ','
        returnData += item[this.dataType] + ','
      })
      if (this.displayData.length > 0) {
        this.displayData = this.displayData.substring(0, this.displayData.length - 1)
      }
      if (returnData.length > 0) {
        returnData = returnData.substring(0, returnData.length - 1)
      }
      if (this.selectedData.length > this.maxNum && this.maxNum !== 0 && this.maxNum !== null) {
        this.$tap.alert('当前模块允许的最大值为' + this.maxNum + '', 'warning')
      } else {
        this.$emit('update:initDisplayData', this.displayData)
        this.$emit('input', returnData)
        this.$emit('confirm', this.selectedData)
        this.refVisible = false
      }
    },
    doClearAll() {
      this.$tap
        .confirm('确定要清空选择？')
        .then((_) => {
          var spitem
          for (var i in this.selectedData) {
             if (this.selectedData[i].code === CHECK_CENTER.CHECK_CENTER) {
               spitem = this.selectedData[i]
             }
          }
          this.selectedData = []
          if (spitem !== null && spitem !== undefined) {
            this.selectedData.push(spitem)
          }
          // this.doConfirm();
        })
        .catch((_) => {})
    },
    openRefDialog() {
      if (this.disabled) {
        return
      }
      this.refVisible = true
    },
    doQueryBySearch() {
      this.queryParam.currentPage = 1
      this.queryParam.totalPage = 0
      this.queryData()
    },
    doQueryMore() {
      if (!this.noMore) {
        this.queryParam.currentPage++
        getAction(this.queryDataUrl, { ...this.queryParam, ...this.externalQueryParam })
          .then((res) => {
            if (res.success) {
              this.dataList.push(...res.result.dataList)
              this.queryParam.totalPage = res.result.totalPage
            } else {
              this.$tap.alert(res.message, 'warning')
            }
          })
          .catch((err) => {})
      }
    },
    resetQueryParam() {
      this.disabledScrollSearch = true
      let exclude = ['sidx', 'sord', 'qry_includeSub', 'currentPage', 'pageSize', 'totalPage']
      for (let key of Object.keys(this.queryParam)) {
        if (!exclude.includes(key)) {
          this.queryParam[key] = ''
        }
      }
      this.queryParam.currentPage = 1
      this.queryParam.totalPage = 0
    },
    doSelectAll() {
      this.dataList.forEach((data, index) => {
        if (this.selectedData.findIndex((item) => item.id === data.id) === -1) {
          this.selectedData.push(data)
        }
      })
    },
    queryData() {
      if (!this.queryDataUrl) {
        this.$tap.alert('请设置加载地址!', 'warning')
        return
      }
      this.isLoading = true
      getAction(this.queryDataUrl, { ...this.queryParam, ...this.externalQueryParam })
        .then((res) => {
          if (res.success) {
            this.dataList = res.result.dataList
            this.queryParam.totalPage = res.result.totalPage
            this.disabledScrollSearch = false
          } else {
            this.$tap.alert(res.message, 'warning')
          }
          this.isLoading = false
        })
        .catch((err) => {
          this.isLoading = false
        })
    },
    addData(data) {
      if (this.singleSelect) {
        this.selectedData = []
      }
      if (this.selectedData.findIndex((item) => item.id === data.id) === -1) {
        this.selectedData.push(data)
      }
    },
    removeData(data) {
      if (data.code !== CHECK_CENTER.CHECK_CENTER) {
      this.selectedData.splice(this.selectedData.findIndex((item) => item.id === data.id), 1)
      }
    },
    initRef() {
      // this.dataList = []
      this.resetQueryParam()
      this.queryData()
      this.queryDefaultSelectedValue()
    },
    queryDefaultSelectedValue() {
      if (!this.queryDataUrl) {
        this.$tap.alert('请设置加载地址!', 'warning')
        return
      }
      this.selectedData = []
      // 打开后，加载选中值的相关数据
      let queryParam = {
        sidx: 'sortcode',
        sord: 'asc',
        qry_codelist: '',
        qry_idlist: '',
        qry_all: '1',
        currentPage: 1,
        pageSize: 10000
      }
      if (this.value && this.value.toString().length > 0) {
        queryParam['qry_' + this.dataType + 'list'] = this.value
        getAction(this.queryDataUrl, queryParam)
          .then((res) => {
            if (res.success) {
              this.selectedData = res.result.dataList.filter((m) => this.value.toString().indexOf(m[this.dataType]) > -1)
            } else {
              this.$tap.alert(res.message, 'warning')
            }
          })
          .catch((err) => {})
      }
    },
    open() {
      this.initRef()
    }
  },
  created() {
    Object.assign(this.queryParam, this.queryDataParam)
  }
}
</script>
<style lang="scss">
.tl-ref-list {
  .el-tag {
    margin: 0 10px 10px 0;
  }
  .el-tag--info {
    cursor: pointer;
  }
}
</style>
